﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Windows.Media;
using CSharp.Libs.Koc;
using CSharp.Libs.Koc.Models;

namespace CSharp.Libs.WPF.UserControls
{
    public class AllianceListViewModel : ViewModelBase
    {
        #region declarations
        private Kernel _KRNL = null;

        private PhpCommand _pcAllianceGetOtherInfo = null;

        private RelayCommand _rcExecuteUrl = null;
        private RelayCommand _rcGotoPage = null;
        private RelayCommand _rcNextPage = null;
        private RelayCommand _rcPreviousPage = null;

        private ObservableCollection<KocAllianceListItem> _ocOtherAlliances = new ObservableCollection<KocAllianceListItem>();

        private Int32 _intServerId = 0;
        private Int32 _intNoOfPages = 0;
        private String _strCurrentPage = "";

        #region constants
        private const String DATE_TIME_STAMP_MASK = "dd.MM.yyyy HH:mm:ss";
        #endregion
        #endregion



        #region constructor / terminator
        public AllianceListViewModel(
            Kernel KRNL)
        {
            _KRNL = KRNL;

            _KRNL.TM.ChatReceived += new TrafficMonitor.ChatReceivedEventHandler(TM_ChatReceived);
        }

        ~AllianceListViewModel()
        {
            if (_KRNL != null)
            {
                if (_KRNL.TM != null)
                {
                    _KRNL.TM.ChatReceived -= TM_ChatReceived;
                }

                _KRNL = null;
            }
        }
        #endregion



        #region event handling
        void TM_ChatReceived(object sender, Koc.KernelModels.ChatReceivedEventArgs crea)
        {
            if (_pcAllianceGetOtherInfo == null)
            {
                _PreparePhpCommands();
                OnPropertyChanged("CanGetAlliList");
                OnPropertyChanged("ServerId");
            }
        }
        #endregion
            
        
        
        #region private functions
        /// <summary>_PreparePhpCommands</summary>
        /// <history>07.07.2011</history>
        /// <history>modified 18.01.2012: switched to PhpCommandGenerator support</history>
        private void _PreparePhpCommands()
        {
            try
            {
                if (PhpCommandGenerator.IsInitialized &&
                    _pcAllianceGetOtherInfo == null)
                {
                    _pcAllianceGetOtherInfo = PhpCommandGenerator.GetPhpCommand(
                        _KRNL.EC,
                        PhpCommands.allianceGetOtherInfo,
                        _intServerId);

                    _pcAllianceGetOtherInfo.Parameters[PhpCommandParameters.PAGE_NO] = "1";
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
                throw;
            }
        }

        #region alliance list
        /// <summary>_GetAlliList</summary>
        /// <history>modified 18.01.2012: switched to PhpCommandGenerator support</history>
        private void _GetAlliList()
        {
            try
            {
                //_PreparePhpCommands();

                if (_pcAllianceGetOtherInfo != null)
                {
                    _ocOtherAlliances.Clear();

                    //check and give server number
                    if (_intServerId == 0) { _intServerId = 1; }
                    if (_pcAllianceGetOtherInfo.PhpUrlServerId != _intServerId)
                    {
                        _pcAllianceGetOtherInfo.PhpUrlServerId = _intServerId;
                    }

                    //get returnvalue
                    Hashtable htResult = null;
                    if(_pcAllianceGetOtherInfo.GetAnswerHashtable(out htResult))
                    {
                        Boolean fResultOk = false;
                        Boolean.TryParse(htResult[constants.KEY_OK].ToString(), out fResultOk);
                        if (fResultOk)
                        {
                            Int32.TryParse(htResult[constants.KEY_NO_OF_PAGES].ToString(), out _intNoOfPages);
                            OnPropertyChanged("NoOfPages");
                            _strCurrentPage = htResult[constants.KEY_CURRENT_PAGE].ToString();
                            OnPropertyChanged("CurrentPage");

                            ArrayList _aryOtherAlliances = htResult[constants.KEY_OTHER_ALLIANCES] as ArrayList;
                            if (_aryOtherAlliances != null)
                            {
                                foreach (Hashtable HT in _aryOtherAlliances)
                                {
                                    try
                                    {
                                        KocAllianceListItem KALI = new KocAllianceListItem();
                                        KALI.AllianceId = HT[constants.KEY_ALLIANCE_ID].ToString();
                                        KALI.Name = HT[constants.KEY_NAME].ToString();
                                        KALI.MembersCount = HT[constants.KEY_MEMBERS_COUNT].ToString();
                                        KALI.Might = Int64.Parse(HT[constants.KEY_MIGHT].ToString()).ToString("0,000");
                                        KALI.Ranking = HT[constants.KEY_RANKING].ToString();
                                        KALI.HostUserId = HT[constants.KEY_HOST_USER_ID].ToString();
                                        KALI.Host = HT[constants.KEY_HOST].ToString();
                                        KALI.HostGenderAndName = HT[constants.KEY_HOST_GENDER_AND_NAME].ToString();
                                        KALI.FounderUserId = HT[constants.KEY_FOUNDER_USER_ID].ToString();
                                        KALI.FounderName = HT[constants.KEY_FOUNDER_NAME].ToString();
                                        KALI.FounderGenderAndName = HT[constants.KEY_FOUNDER_GENDER_AND_NAME].ToString();
                                        _ocOtherAlliances.Add(KALI);
                                    }
                                    catch (Exception ex)
                                    {
                                        _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
                                    }
                                }
                            }
                            else
                            {
                                //_strResult = "Server didn't return ArrayList.";
                            }
                        }
                        else
                        {
                            //_strResult = "Server returned false.";
                        }
                    }
                    else
                    {
                        //_strResult = "Execute didn't return true.";
                    }
                }
                else
                {
                    //_strResult = "URL is not valid.";
                }

                OnPropertyChanged("OtherAlliances");
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>_GotoPage</summary>
        /// <history>modified 18.01.2012: switched to PhpCommandGenerator support</history>
        private void _GotoPage()
        {
            try
            {
                if (_pcAllianceGetOtherInfo != null)
                {
                    if (_pcAllianceGetOtherInfo.Parameters[PhpCommandParameters.PAGE_NO] != _strCurrentPage)
                    {
                        _GetAlliList();
                    }
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>_NextPage</summary>
        /// <history>modified 18.01.2012: switched to PhpCommandGenerator support</history>
        private void _NextPage()
        {
            try
            {
                if (_pcAllianceGetOtherInfo != null)
                {
                    Int32 intPageNo = 0;
                    if (Int32.TryParse(_pcAllianceGetOtherInfo.Parameters[PhpCommandParameters.PAGE_NO].ToString(), out intPageNo))
                    {
                        if (intPageNo == _intNoOfPages)
                        {
                            intPageNo = 1;
                        }
                        else
                        {
                            intPageNo++;
                        }

                        _pcAllianceGetOtherInfo.Parameters[PhpCommandParameters.PAGE_NO] = intPageNo.ToString();
                        _GetAlliList();

                    }
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>_PreviousPage</summary>
        /// <history>modified 18.01.2012: switched to PhpCommandGenerator support</history>
        private void _PreviousPage()
        {
            try
            {
                if (_pcAllianceGetOtherInfo != null)
                {
                    Int32 intPageNo = 0;
                    if (Int32.TryParse(_pcAllianceGetOtherInfo.Parameters[constants.KEY_NO_OF_PAGES].ToString(), out intPageNo))
                    {
                        if (intPageNo == 1)
                        {
                            intPageNo = _intNoOfPages;
                        }
                        else
                        {
                            intPageNo--;
                        }

                        _pcAllianceGetOtherInfo.Parameters[PhpCommandParameters.PAGE_NO] = intPageNo.ToString();
                        _GetAlliList();
                    }
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }
        #endregion
        #endregion



        #region interface
        #region properties
        #region alliance list
        public Int32 ServerId
        {
            get
            {
                return _intServerId;
            }
            set
            {
                if (value > 0 && value <= constants.MAX_SERVER_NUMBER)
                {
                    _intServerId = value;
                }
            }
        }

        public ICommand GetAlliList
        {
            get
            {
                if (_rcExecuteUrl == null)
                {
                    _rcExecuteUrl = new RelayCommand(
                        param => this._GetAlliList(),
                        param => this.CanGetAlliList);
                }
                return _rcExecuteUrl;
            }
        }
        public Boolean CanGetAlliList
        {
            get
            {
                return PhpCommandGenerator.IsInitialized;
            }
        }

        public ICommand GotoPage
        {
            get
            {
                if (_rcGotoPage == null)
                {
                    _rcGotoPage = new RelayCommand(
                        param => this._GotoPage(),
                        param => this.CanGotoPage);
                }
                return _rcGotoPage;
            }
        }
        public Boolean CanGotoPage
        {
            get
            {
                return PhpCommandGenerator.IsInitialized && _intNoOfPages > 0;
            }
        }

        public ICommand NextPage
        {
            get
            {
                if (_rcNextPage == null)
                {
                    _rcNextPage = new RelayCommand(
                        param => this._NextPage(),
                        param => this.CanNextPage);
                }
                return _rcNextPage;
            }
        }
        public Boolean CanNextPage
        {
            get
            {
                return PhpCommandGenerator.IsInitialized && _intNoOfPages > 0;
            }
        }

        public ICommand PreviousPage
        {
            get
            {
                if (_rcPreviousPage == null)
                {
                    _rcPreviousPage = new RelayCommand(
                        param => this._PreviousPage(),
                        param => this.CanPreviousPage);
                }
                return _rcPreviousPage;
            }
        }
        public Boolean CanPreviousPage
        {
            get
            {
                return PhpCommandGenerator.IsInitialized && _intNoOfPages > 0;
            }
        }

        public String PageNo
        {
            get
            {
                if (_pcAllianceGetOtherInfo != null)
                {
                    return _pcAllianceGetOtherInfo.Parameters[PhpCommandParameters.PAGE_NO].ToString();
                }
                else
                {
                    return "";
                }
            }
            set
            {
                if (_pcAllianceGetOtherInfo != null)
                {
                    Int32 intPageNo = -1;
                    if (Int32.TryParse(value, out intPageNo))
                    {
                        if (intPageNo > 0)
                        {
                            _pcAllianceGetOtherInfo.Parameters[PhpCommandParameters.PAGE_NO] = value;
                        }
                    }
                }
            }
        }

        public Int32 NoOfPages
        {
            get
            {
                return _intNoOfPages;
            }
        }

        public String CurrentPage
        {
            get
            {
                return _strCurrentPage;
            }
        }

        public ObservableCollection<KocAllianceListItem> OtherAlliances
        {
            get
            {
                return _ocOtherAlliances;
            }
        }
        #endregion
        #endregion

        #region methods
        #endregion
        #endregion
    }
}
